package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.message.*;
import sk.naive.talker.util.Utils;

import java.rmi.RemoteException;
import java.util.*;

/**
 * Go commnad.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.18 $ $Date: 2005/01/19 22:41:27 $
 */
public class Go extends AbstractCommand {
	public void exec()
		throws CommandException,
		RemoteException
	{
		if (params == null || params.length() == 0) {
			sendMisusageWarning();
			return;
		}

		Collection<String> exitNames;
		Location originalLoc = new LocationHelper(commandDispatcher).locationForUser(user);
		if (originalLoc != null) {
			exitNames = new TreeSet<String>();
			for (Iterator i = originalLoc.nearLocations().iterator(); i.hasNext(); ) {
				exitNames.add(((Location) i.next()).getName());
			}
		} else {
			exitNames = commandDispatcher.locationFinder().locationNames();
		}
		String targetLoc = Utils.findFirstInCollection(params, exitNames, true);
		if (targetLoc == null) {
			user.getProperties().put(DefaultMessageFactory.CTXKEY_VAL, params);
			sendHelper().sendMessage(user, "go.noWay");
			return;
		}
		Location newLoc = commandDispatcher.locationFinder().findLocationByName(targetLoc);
		if (originalLoc != null) {
			originalLoc.userOut(user);
			ctxSet(DefaultMessageFactory.CTXKEY_VAL, newLoc.getProperties());
			goPhrase(user, "go.outphr", originalLoc);
		}
		goPhrase(user, "go.inphr", newLoc);
		newLoc.userIn(user);
		commandDispatcher.process("look", user, null);
	}

	private void goPhrase(User user, String phrase, Location loc) throws RemoteException {
		sendMassMessage(getMessage(phrase, user.getProperties()), loc.users(), null, Category.INOUT);
	}
}
